package cn.flying.cloud.tool.ops.redis;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.base.redis.service.RedisService;

/**
 * Redis缓存处理 前端控制器
 *
 * @author: admin
 * @date: 2025年04月01日 21:12
 * @version: 1.0
 */
@RestController
@RequestMapping("/tool/redis")
public class RedisController {

    @Resource
    private RedisService redisService;

    /**
     * 获取Redis所有的缓存
     *
     * @return
     */
    @RequestMapping("getAllCache")
    public Rt<?> getAllCacheDataWithScan() {
        RedisTemplate<String, Object> redisTemplate = redisService.redisTpl();

        List<CacheVo> list = new ArrayList<>();

        Cursor<byte[]> cursor = redisTemplate.getConnectionFactory().getConnection().scan(ScanOptions.scanOptions().match("*").build());

        while (cursor.hasNext()) {
            String key = new String(cursor.next());
            if (key.startsWith("spring:session")) {
                continue;
            }
            DataType type = redisTemplate.type(key);
            if (type == DataType.STRING) {
                Object value = redisTemplate.opsForValue().get(key);
                list.add(new CacheVo(key, value, type.code()));
            } else if (type == DataType.HASH) {
                Object value = redisTemplate.opsForHash().entries(key);
                list.add(new CacheVo(key, value, type.code()));
            }

        }
        return Rt.success(list);
    }

    /**
     * 获取Redis缓存过期时间
     *
     * @return
     */
    @RequestMapping("getExpire")
    public Rt<?> getExpire(String type) {
        RedisTemplate<String, Object> redisTemplate = redisService.redisTpl();
        Long expire = redisTemplate.getExpire(type);
        return Rt.success(expire);
    }

    /**
     * 删除缓存
     *
     * @return
     */
    @RequestMapping("delete")
    public Rt<?> delete(String key, String field) {
        if (Ft.String.isBlank(field)) {
            redisService.del(key);
        } else {
            redisService.hdel(key, field);
        }
        return Rt.success("删除成功！");
    }
}
